(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var TABLE_CACHE_DATA = 'cache_data';
	var TABLE_EXIST = String.format("SELECT name FROM sqlite_master WHERE type='table' AND name=\'%s\'", TABLE_CACHE_DATA);
	var DROP_CACHE_DATA = String.format('DROP TABLE IF EXISTS %s', TABLE_CACHE_DATA);
	var CREATE_CACHE_DATA = String.format('CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, key TEXT, value TEXT)', TABLE_CACHE_DATA);
	var CACHE_FOLDER = '../Library/Caches';
	var DB_FILE_NAME = 'cachingdb';
	var CACHE_IMAGE_FOLDER = '../Library/Caches/Images';

	function OpenConnection() {
		var folder = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, CACHE_FOLDER);
		var file = Ti.Filesystem.getFile(folder.nativePath, DB_FILE_NAME + '.sqlite');
		var db = Ti.Database.install(file.nativePath, DB_FILE_NAME);
		return db;
	};

	var cache = {};
	cache.setup = function() {
		var folder = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, CACHE_FOLDER);
		if (!folder.exists()) {
			folder.createDirectory();
		}
		var file = Ti.Filesystem.getFile(folder.nativePath, DB_FILE_NAME + '.sqlite');
		if (!file.exists()) {
			file.createFile();
			var db = Ti.Database.install(file.nativePath, DB_FILE_NAME);
			db.execute(DROP_CACHE_DATA);
			db.execute(CREATE_CACHE_DATA);
			db.close();
		}
	};

	cache.cache_data = {};
	cache.cache_data.get = function(key) {
		var result;
		var db = OpenConnection();
		var rows = db.execute(String.format("SELECT value FROM %s WHERE key = \'%s\'", TABLE_CACHE_DATA, key));
		if (rows.isValidRow()) {
			result = rows.field(0);
		}
		rows.close();
		db.close();
		return $.isNull(result) ? '' : $.decode_single_quotes(result);
	};
	cache.cache_data.remove = function(key) {
		var db = OpenConnection();
		db.execute(String.format("DELETE FROM %s WHERE key = %s", TABLE_CACHE_DATA, key));
		db.close();
	};
	cache.cache_data.remove_when_logout = function() {
		var db = OpenConnection();
		db.execute(String.format("DELETE FROM %s WHERE key NOT IN('GetStaticContent','Retailers', 'RetailerStores')", TABLE_CACHE_DATA));
		db.close();
		// cache.cache_image.remove_all();
	};
	cache.cache_data.insert_or_update = function(key, value) {
		value = value.replace(/Helvetica World/g, "Helvetica-World");
		//TODO:Fix font-family, please remove this line when content has been fixed.
		value = $.encode_single_quotes(value);
		var db = OpenConnection();
		var rows = db.execute(String.format("SELECT value FROM %s WHERE key = \'%s\'", TABLE_CACHE_DATA, key));
		if (rows.isValidRow()) {
			db.execute(String.format("UPDATE %s SET value = \'%s\' WHERE key = \'%s\'", TABLE_CACHE_DATA, value, key));
		} else {
			db.execute(String.format("INSERT INTO %s (key, value) VALUES (\'%s\',\'%s\')", TABLE_CACHE_DATA, key, value));
		}
		rows.close();
		db.close();
	};

	cache.cache_image = {};
	cache.cache_image.init = function(url, obj, callBack) {
		var filename = _.escape(url);
		var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, CACHE_IMAGE_FOLDER, filename);
		if (file.exists()) {
			if (obj)
				obj.image = file.nativePath;
			callBack && callBack(file.nativePath);
			file = null;
		} else {
			var g = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, CACHE_IMAGE_FOLDER);
			if (!g.exists()) {
				g.createDirectory();
			};
			var xhr = Ti.Network.createHTTPClient();
			xhr.onload = function() {
				if (xhr.status == 200) {
					file.write(xhr.responseData);
					if (obj)
						obj.image = file.nativePath;
					callBack && callBack(file.nativePath);
					file = null;
				};
			};
			xhr.open('GET', url);
			xhr.send();
		};
	};
	cache.cache_image.remove_all = function() {
		var imageFolder = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, CACHE_IMAGE_FOLDER);
		if (imageFolder.exists()) {
			imageFolder.deleteDirectory(true);
		};
	};

	module.exports = cache;
})();
